<template>
    <div class="chat">
        <div class="left">
            <!--<div class="left-inform">
                <div class="user">
                    <img src="../../static/img/ico.jpg" />
                </div>
                <div class="menu">
                    <div class="menu-item" :class="{active: showchat}" @click="showChat">
                        <span class="menu-radius chatfont icon-chat">&#xe605;</span>
                        <p>消息</p>
                    </div>
                    <div class="menu-item" :class="{active: showgroup}" @click="showGroup">
                        <span class="menu-radius chatfont">&#xe624;</span>
                        <p>群组</p>
                    </div>
                </div>
                <div class="setup"></div>
            </div>-->
            <div class="left-list">
                <div class="chat-list" v-if="!group">
                    <div class="search">
                        <el-input autocomplete="off"
                                  size="medium"
                                  clearable
                                  v-model="searchKey"
                                  placeholder="搜索"></el-input>
<!--                        <input autocomplete="off" v-model="searchKey" id="username" type="text"  placeholder="搜索" />-->
                    </div>
                    <ul  class="user-list">
                        <li class="item" :class="{active:username===charData.to}" v-for="(username,index) in userListFilter" :key="index" @click="toggleSession(username,`../../static/img/0${userImgIndex(username)%10+1}.gif`)">
                            <div class="userPhoto" :class="{active:userSocketList.includes(username)}">
                                <img v-if="userList.includes(username)" :src="`../../static/img/0${userImgIndex(username)%10+1}.gif`" />
                                <div class="roomPhoto" v-else>饭</div>
                            </div>
                            <div class="userInfo">
                                <strong>{{/groupChat/.test(username)?'恰饭群':username}}</strong>
                                <span>{{(socketUserInfo(username).endMsg || "").replace(/<[^>]+>/g,"").replace(/&nbsp;/g, '')}}</span>
                            </div>
                            <span class="drag" v-if="socketUserInfo(username).unreadCount">{{socketUserInfo(username).unreadCount}}</span>
<!--                            <span class="close" @click.stop="delUser(item.username)"></span>-->
                        </li>
                    </ul>
                </div>
                <div  class="group"  v-if="group">
                    <div class="group-tab">
                        <div :class="{active:isgroup}" @click="isGroup">群</div>
                        <div :class="{active:!isgroup}" @click="isMuc">讨论组</div>
                    </div>
                    <div class="group-box">
                        <div class="group-list" v-if="isgroup">
                            您暂时还没有添加任何群
                        </div>
                        <div class="muc-list" v-if="!isgroup">
                            您暂时还没有添加任何讨论组
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- left dom end -->

        <!-- right dom start -->
        <div class="chatImg" v-show="!isChat">
            <!--<img src="../../static/img/ico.png" />-->
            <p>欢迎使用!</p>
        </div>
        <div class="right" v-show="isChat">
            <!-- top dom start -->
            <div class="title">
                <div class="userPhoto" :class="{active:userSocketList.includes(charData.to)}">
                    <img v-if="userList.includes(charData.to)" :src="charInfo.img" />
                    <div v-else class="roomPhoto">饭</div>
                </div>
                <div class="userInform">
                    <strong>{{/groupChat/.test(charInfo.username)?'恰饭群':charInfo.username}}</strong>
                    <span>{{charInfo.endMsg}}</span>
                </div>
                <!-- <div class="operation">
                  <div class="sendfile" title="发送文件">
                      <input id="file" type="file"  multiple />
                  </div>
                  <span class="information" style="display:none"></span>
                </div> -->
            </div>
            <!-- top dom end -->

            <!-- content dom start -->
            <div class="content">
                <div id="message" class="message">
                    <chat-item v-for="(i,index) in chatMessageList" :key="index" :item="i"></chat-item>
                </div>
            </div>
            <!-- content dom end -->

            <!-- bottom dom start -->
            <div class="edit">
                <div class="bar"unselectable="on" onmousedown="return false">
                    <span class="font J-EditItem" unselectable="on" onmousedown="return false"></span>
                    <span class="face J-EditItem" unselectable="on" onmousedown="return false"></span>
                    <span class="shake J-EditItem" unselectable="on" onmousedown="return false"></span>
                    <span class="det J-EditItem" unselectable="on" onmousedown="return false"></span>
                    <span class="img J-EditItem" unselectable="on" onmousedown="return false"></span>
                    <span class="muc J-EditItem" unselectable="on" onmousedown="return false" @click="showMucBox">&#xe625;</span>
                    <span class="cut J-EditItem" unselectable="on" onmousedown="return false"></span>
                    <strong class="record fr" @click="getChatHistory">查看消息记录</strong>
                </div>
                <div id="textarea" @keydown.enter="chatSubmit($event)" class="textarea J-Edit" contenteditable="true" >
                </div>
            </div>
            <!-- bottom dom end  @keyup.enter="clearChat($event)"-->

        </div>
        <!-- right dom end -->

        <!-- add muc -->
        <div class="mask" v-if="mask"></div>
        <div class="muc-box" v-if="muc">
            <div class="title"><span class="fl">添加讨论组</span><span class="fr" @click="muc=false;mask=false">&#xe641;</span></div>
            <div class="muc-cont">
                <div>
                </div>
                <div>

                </div>
            </div>
        </div>
    </div>
</template>
<!--<script src="../util/chat.js"></script>-->
<script>
import moment from 'moment'
import ChatItem from '@/components/chat-item'

import {getChat, getUser,getChatInfo,readMsg} from '@/api/user'
import {mapGetters} from "vuex";
import store from "@/store";
import concat from 'lodash/concat'
import uniqBy from 'lodash/uniqBy'
import sortBy from 'lodash/sortBy'
import isEmpty from 'lodash/isEmpty'
import debounce from 'lodash/debounce'
import cloneDeep from 'lodash/cloneDeep'
import flatten from 'lodash/flatten'

export default {
    name: "chat",
    computed: {
        ...mapGetters([
            'socket',
            'userList',
            'chatToUser',
            'userSocketList',
            'messageList',
            'userMessageInfo',
            'socketInfo'
        ]),
        userListFilter(){
            // console.log(this.searchKey && this.searchUserList)
            return this.searchKey && this.searchUserList || concat([`groupChat_${this.userInfo.username}`],this.userList)
        },
        socketUserInfo(){
            return username=>{
                return this.socketInfo[username] || {username,unreadCount:0,endMsg:""}
            }
        },
        chatMessageList(){
            const isGroupChat=/groupChat/.test(this.charData.to);
            return this.charData.to && this.messageList[isGroupChat?`groupChat_${this.userInfo.username}`:this.charData.to] || []
        }
    },
    components: {
        ChatItem
    },
    data(){
        return {
            searchUserList:[],
            searchKey:"",
            subtractDay:0,
            isSending:false,
            charData:{
                msg:"",
                from:"",
                to:"",
            },
            charInfo:{
                img:'../../static/img/ico.jpg',
                username:'',
            },
            current: {},
            cacheReadCount:{},
            group: false,
            isgroup: true,
            isChat: false,
            mask: false,
            muc: false,
            showchat: true,
            showgroup: false,
            userid: window.localStorage.getItem('uid')
        }
    },
    created() {
        this.charData.from=this.userInfo.username
    },
    watch:{
        searchKey(v){
            v && this.debounceMethod()
        }
    },
    beforeDestroy() {
        this.chatToUser && this.userInfo.authorization && readMsg({senduser:this.chatToUser,
            unreadCount:this.socketUserInfo(this.chatToUser).unreadCount,
            msg:this.socketUserInfo(this.chatToUser).endMsg})
        this.$store.commit('exclude/SET_SOCKET_CHAT_TO',"")
    },
    methods: {
        userImgIndex(username){
            return this.userList.findIndex(i=>username.includes(i))
        },
        socketItem(){

        },
        debounceMethod:debounce(function (){
            const userList=concat([`groupChat_${this.userInfo.username}`],this.userList).filter(i=>i.includes(this.searchKey))
            // const messageList=flatten(Object.values(this.messageList)).filter(i=>i.msg.includes(this.searchKey))
            // this.searchUserList=concat(userList,messageList)
            this.searchUserList=userList
        },1000),
        getChatHistory(){
            const senduser=this.charData.to
            if(this.userMessageInfo.create_time && !this.subtractDay){
                const today=moment().format("YYYY-MM-DD");
                this.subtractDay=moment(today).diff(moment(this.userMessageInfo.create_time), 'day');
            }
            const create_time=moment().subtract(this.subtractDay,"days").format("YYYY-MM-DD");
            if(senduser){
                const from=`groupChat_${senduser}`
                getChatInfo({senduser,create_time,username:this.userInfo.username}).then(res=>{
                    const messageList=cloneDeep(this.messageList)
                    messageList[senduser]=concat(res.data.chat,messageList[senduser])
                    messageList[from]=concat(res.data.groupChat,messageList[from])
                    if(res.data.length){
                        this.subtractDay--
                    }
                    const count=this.socketUserInfo(senduser).unreadCount-messageList[senduser].length
                    const countGroup=this.socketUserInfo(from).unreadCount-messageList[from].length
                    const socketInfo={
                        unreadCount:count<0?0:count,
                        msg:(messageList[senduser].slice(-1)[0] || {}).msg,
                        from:senduser,
                    }
                    const socketInfoGroup={
                        unreadCount:countGroup<0?0:countGroup,
                        msg:(messageList[from].slice(-1)[0] || {}).msg,
                        from:senduser,
                    }
                    this.$store.commit('exclude/SET_MESSAGE_LIST',messageList)
                    this.$store.commit('user/SET_SOCKET_INFO', socketInfo)
                    this.$store.commit('user/SET_SOCKET_INFO', socketInfoGroup)
                })
            }
        },
        chatSubmit(e){
            if(isEmpty(this.socket)){
                this.$store.commit('exclude/SET_SOCKET',io.connect(this.baseURL, {
                    extraHeaders:{
                        authorization: this.userInfo.authorization
                    }
                }));
            }
            //内容为空或者正在发送
            // const content=e.target.innerHTML
            if(!e.target.innerHTML.replace(/\<div><br><\/div>/g,"") || this.apiLoading) return;
            this.$store.commit('exclude/SET_LOADING',true)
            this.charData.msg=e.target.innerHTML
            //群聊
            const isGroupChat=/groupChat/.test(this.charData.to);
            this.socket.emit(isGroupChat?'groupChat':'send', this.charData,done=>{
                if(done){
                    const messageList=cloneDeep(this.messageList)
                    messageList[this.charData.to].push({
                        ...(isGroupChat?{from:this.userInfo.username,to:'groupChat'}
                            :{from:this.userInfo.username}),
                        msg:this.charData.msg,className:'message-right'
                    })
                    this.$store.commit('exclude/SET_MESSAGE_LIST',messageList)
                    this.$store.commit('user/SET_SOCKET_INFO', {
                        from:this.charData.to,
                        msg:this.charData.msg,
                        unreadCount:0
                    })
                    this.$nextTick(()=>{
                        document.getElementById("message").scrollTop = 1000000000;
                        document.getElementById('textarea').innerHTML="";
                        this.$store.commit('exclude/SET_LOADING',false)
                    })
                }else {
                    this.$message.error('消息发送失败，请稍后重试')
                    this.$store.commit('exclude/SET_LOADING',false)
                }
            });
            // this.socket.emit('broadcast', this.charData);
        },
        showChat() {
            this.group = false;
            this.showchat = true;
            this.showgroup = false;
        },
        showGroup() {
            this.group = true;
            this.showchat = false;
            this.showgroup = true;
        },
        isGroup() {
            this.isgroup = true;
        },
        isMuc() {
            this.isgroup = false;
        },
        showMucBox() {
            this.mask = true;
            this.muc = true;
        },
        delUser(item) {
            /*var index = this.userList.indexOf(item);
            this.userList.splice(index, 1);*/
        },
        toggleSession(username,img) {
            //校准chat对象
            /*const isRoom=(this.socket.io.opts.query || {}).roomName
            if(this.userList.includes(username)){
                isRoom && this.$store.commit('exclude/SET_SOCKET',io.connect(this.baseURL, {extraHeaders:{
                        authorization: this.userInfo.authorization
                    }}));
            }else {
                !isRoom && this.$store.commit('exclude/SET_SOCKET',io.connect(this.baseURL, {
                    query: {
                        roomName: username
                    },
                    extraHeaders:{
                        authorization: this.userInfo.authorization
                    }
                }));
            }*/
            this.$store.commit('exclude/SET_SOCKET_CHAT_TO',username)
            const oldUsername=this.charData.to
            if(oldUsername){
                const oldObj=this.messageList[oldUsername].slice(-1)[0] || {}
                oldObj.from=/groupChat/.test(oldUsername)?oldObj.from:oldUsername
                const oldUnreadCount=this.socketUserInfo(oldUsername).unreadCount-this.chatMessageList.length
                oldObj.unreadCount=oldUnreadCount<0?0:oldUnreadCount
                this.$store.commit('user/SET_SOCKET_INFO', oldObj)
                const oldReadCount=this.socketUserInfo(oldUsername).unreadCount
                if(this.cacheReadCount[oldUsername]!==oldReadCount){
                    readMsg({senduser:oldUsername,unreadCount:oldReadCount}).then(res=>{
                        if(res.data.from){
                            this.cacheReadCount[res.data.from]=res.data.unreadCount
                        }
                    })
                }
            }
            //校准unread,对比信息数量
            this.charInfo.img=img
            this.charInfo.username=username
            this.charData.to = username;
            //和谁交谈的信息,
            if(this.userMessageInfo.create_time && !this.chatMessageList.length){
                const chatToSelfInfo=this.userMessageInfo.chatToSelInfo.filter(i=>i.from===username)
                const chatToOtherInfo=this.userMessageInfo.chatToOtherInfo.filter(i=>i.to===username)
                const result=sortBy(concat(chatToSelfInfo,chatToOtherInfo),'create_time')
                const messageList=cloneDeep(this.messageList)
                if(/groupChat/.test(username)){
                    messageList[username]=concat(this.userMessageInfo.chatToGroupInfo,messageList[username])
                }else {
                    messageList[username]=concat(result,messageList[username])
                }
                this.$store.commit('exclude/SET_MESSAGE_LIST',messageList)
            }
            const newObj=this.messageList[username].slice(-1)[0] || {}
            newObj.from=/groupChat/.test(username)?newObj.from:username
            const newUnreadCount=this.socketUserInfo(username).unreadCount-this.chatMessageList.length
            newObj.unreadCount=newUnreadCount<0?0:newUnreadCount
            this.$store.commit('user/SET_SOCKET_INFO', newObj)
            //更新endMsg
            this.isChat = true;
            this.$nextTick(()=>{
                document.getElementById("message").scrollTop = 1000000000;
            })
        }
    }
}
</script>

<style scoped lang="scss">
    .roomPhoto {
        background-color:#E17076;
        color:#ffffff;
        text-align: center;
        font-size:18px;
        border-radius: 40px;
    }
    .chat {
        height: calc(100vh - 80px);
        display: flex;
    }
    @font-face {
        font-family: 'chatfont';  /* project id 351760 */
        src: url('~@/styles/iconfont.ttf') format('truetype');
    }
    @import "~@/styles/chat.scss";
</style>
